package com.nju.edu.android_app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.nju.edu.android_app.callback.GetIdListener;
import com.nju.edu.android_app.callback.GetWeiBoListener;
import com.nju.edu.android_app.callback.UserShowListener;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.api.WeiboAPI.FEATURE;
import com.weibo.sdk.android.demo.R;
import com.weibo.sdk.android.keep.AccessTokenKeeper;
import com.weibo.sdk.android.util.Utility;

public class MainActivity extends Activity {

	private Weibo mWeibo;
	public final static int num_weibo_toget=1;
	private static final String CONSUMER_KEY = "942300461";
	private static final String REDIRECT_URL = "http://www.sina.com";
	public static Oauth2AccessToken accessToken;
	public static final String TAG = "sinasdk";
	public static long maxid=0;
	public StreamAdapter adapter;
	public StatusesAPI statusesAPI=null;
	TabHost tabHost;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		/*
		 * 网络设置
		 */
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork() 
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		adapter = new StreamAdapter(this);
		((ListView) findViewById(R.id.main_list)).setAdapter(adapter); 
		
		mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		ImageButton refresh = (ImageButton) findViewById(R.id.refreshButton);
		MainActivity.accessToken = AccessTokenKeeper.readAccessToken(this);
		if (accessToken.getToken()=="") {
			System.out.println("为空");
			mWeibo.authorize(MainActivity.this, new AuthDialogListener());
		}
		else {
			SharedPreferences pref = this.getSharedPreferences(AccessTokenKeeper.PREFERENCES_NAME, Context.MODE_APPEND);
			String name=pref.getString("username", "");
			MainActivity.maxid=pref.getLong("maxid", 0);
			TextView textView=(TextView)MainActivity.this.findViewById(R.id.user_name);
			textView.setText(name);
			accessToken=AccessTokenKeeper.readAccessToken(this);
			/*
			 * 获取最新微博
			 */
			this.statusesAPI=new StatusesAPI(accessToken);
			statusesAPI.homeTimeline(maxid, 0, num_weibo_toget, 1, false, FEATURE.ALL,
					false, new GetWeiBoListener(this));
			System.out.println("发出请求");
		}
		refresh.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					statusesAPI.homeTimeline(0, 0, num_weibo_toget, 1, false, FEATURE.ALL,
							false, new GetWeiBoListener(MainActivity.this));
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.refreshpressed));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.refresh));
				}
				return false;
			}
		});

		// cancelBtn.setOnClickListener(new OnClickListener() {
		// public void onClick(View v) {
		// AccessTokenKeeper.clear(MainActivity.this);
		// }
		if (MainActivity.accessToken.isSessionValid()) {
			Weibo.isWifi = Utility.isWifi(this);
			try {
				Class sso = Class.forName("com.weibo.sdk.android.api.WeiboAPI");
			} catch (ClassNotFoundException e) {
				Log.i(TAG, "com.weibo.sdk.android.api.WeiboAPI not found");
			}
		}
		//if((adapter = this.readPreferences())==null)
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/*
	 * 跳转到微博详细信息页面
	 */
	public void showDetail(View v) {
		Intent intent = new Intent(this, DetailActivity.class);
		ViewGroup view = (ViewGroup) v;
		intent.putExtra("id", (Long)view.getTag());
		startActivity(intent);
	}
	
	/*
	 * 跳转到设置界面
	 */
	
	public void setting(View v)
	{
//		Intent intent=new Intent(this,SettingsActivity.class);
//		startActivity(intent);
	}

	/*
	 * 发布微博
	 */
	public void sendWeibo(View v)
	{
		Intent intent=new Intent(this,WriteActivity.class);
		startActivity(intent);
	}
	
	/*
	 * 负责处理更新获得的新微博
	 */
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(1==msg.what)
			{
			Bundle b = msg.getData();
			MainActivity.this.adapter.insert((new StreamItem(MainActivity.this, b
					.getString("url"), b.getString("pic_url"), b.getString("name"), b
					.getString("text"), b.getLong("id"),b.getString("source"))),0);
			}
			else if(0==msg.what)
			{
				Toast.makeText(MainActivity.this, "无微博更新", Toast.LENGTH_SHORT)
				.show();
			}
			super.handleMessage(msg);
		}

	};
	
	@Override
	public void onStop()
	{
		//AccessTokenKeeper.keepAccessToken(this, MainActivity.accessToken);
//		ArrayList list=new ArrayList<StreamItem>();
//		for(int i=0;i<this.adapter.getCount();i++){
//			list.add(this.adapter.getItem(i));
//		}
//		SharedPreferences preferences = getSharedPreferences("stream_adapter", MODE_PRIVATE);  
//	    // 创建字节输出流  
//	    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
//	    try {  
//	        // 创建对象输出流，并封装字节流  
//	        ObjectOutputStream oos = new ObjectOutputStream(baos);  
//	        // 将对象写入字节流  
//	        System.out.println(list.size());
//	        oos.writeObject(list);  
//	        // 将字节流编码成base64的字符窜  
//	        String adapter_Base64 = new String(Base64.encode(baos.toByteArray(), 0));  
//	        Editor editor = preferences.edit();  
//	        editor.putString("stream_item", adapter_Base64);  
//	        editor.commit();  
//	    } catch (IOException e) {  
//	        // TODO Auto-generated  
//	    }  
//	    Log.i("ok", "存储成功"); 
		SharedPreferences pref = getSharedPreferences(AccessTokenKeeper.PREFERENCES_NAME, Context.MODE_APPEND);
		Editor editor = pref.edit();
		editor.putLong("maxid", maxid);
		editor.commit();
		super.onStop();
	}
	
	/*
	 * 负责获取登录用户的详细信息
	 */
	public Handler getUserInfo =new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			Long uid= b.getLong("uid");
			UsersAPI usersAPI=new UsersAPI(accessToken);
			usersAPI.show(uid, new UserShowListener(MainActivity.this));
			super.handleMessage(msg);
		}
	};

	/*
	 * 负责显示登录用户信息
	 */
	
	public Handler showUserInfo =new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle=msg.getData();
			String name= bundle.getString("name");
			SharedPreferences pref = MainActivity.this.getSharedPreferences(AccessTokenKeeper.PREFERENCES_NAME, Context.MODE_APPEND);
			Editor editor = pref.edit();
			editor.putString("username", name);
			editor.commit();
			TextView textView=(TextView)MainActivity.this.findViewById(R.id.user_name);
			textView.setText(name);
		}
	}
	;
	
	
	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			MainActivity.accessToken = new Oauth2AccessToken(token, expires_in);
			if (MainActivity.accessToken.isSessionValid()) {
				try {
					Class sso = Class
							.forName("com.weibo.sdk.android.api.WeiboAPI");
				} catch (ClassNotFoundException e) {
					Log.i(TAG, "com.weibo.sdk.android.api.WeiboAPI not found");
				}
				AccessTokenKeeper.keepAccessToken(MainActivity.this,
						accessToken);
				Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT)
						.show();
				/*
				 * 获得登录用户ID
				 */
				AccountAPI accountAPI=new AccountAPI(accessToken);
				accountAPI.getUid(new GetIdListener(MainActivity.this));
				MainActivity.this.statusesAPI=new StatusesAPI(accessToken);
				MainActivity.this.statusesAPI.homeTimeline(0, 0, num_weibo_toget, 1, false, FEATURE.ALL,
						false, new GetWeiBoListener(MainActivity.this));
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public StreamAdapter readPreferences(){
		StreamAdapter sa = new StreamAdapter(this);  
	    SharedPreferences preferences = getSharedPreferences("stream_adapter", MODE_PRIVATE);  
	    String productBase64 = preferences.getString("stream_item", "");  
	              
	    //读取字节  
	    byte[] base64 = Base64.decode(productBase64.getBytes(), 0);  
	      
	    //封装到字节流  
	    ByteArrayInputStream bais = new ByteArrayInputStream(base64);  
	    try {  
	        //再次封装  
	        ObjectInputStream bis = new ObjectInputStream(bais);  
	        try {  
	            //读取对象  
	        	ArrayList list=(ArrayList)bis.readObject();
	            for(int i=0;i<list.size();i++){
	            	sa.add((StreamItem)list.get(i));
	            }
	            System.out.println(sa.getCount());
	        } catch (ClassNotFoundException e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	    } catch (StreamCorruptedException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    } catch (IOException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    }  
	    return sa;  
	}
}
